package controller

import (
	"context"
	"github.com/RaymondCode/simple-demo/entity/myerr"
	"github.com/RaymondCode/simple-demo/entity/param"
	"github.com/RaymondCode/simple-demo/entity/response"
	"github.com/RaymondCode/simple-demo/service/impl"
	"github.com/RaymondCode/simple-demo/util/webutil"
	"github.com/cloudwego/hertz/pkg/app"
	"log"
	"net/http"
	"strconv"
)

// Register 用户注册
func Register(ctx context.Context, c *app.RequestContext) {
	var user param.User
	user.UserName = c.Query("username")
	user.Password = c.Query("password")
	if user.UserName == "" || user.Password == "" {
		log.Println("用户名或密码不能为空！")
		c.JSON(http.StatusBadRequest, response.Response{Message: "用户名或密码不能为空！"})
		return
	}
	userId, token, err := serviceimpl.NewUserService().Register(user)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusInternalServerError, response.ErrorResponse(err))
		return
	}
	c.JSON(http.StatusOK, response.Register{
		Response: response.Ok,
		UserId:   userId,
		Token:    token,
	})
}

// Login 用户登陆
func Login(ctx context.Context, c *app.RequestContext) {
	var user param.User
	user.UserName = c.Query("username")
	user.Password = c.Query("password")
	if user.UserName == "" || user.Password == "" {
		c.JSON(http.StatusBadRequest, response.SystemError)
		return
	}
	userId, token, err := serviceimpl.NewUserService().Login(user)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusProxyAuthRequired, response.ErrorResponse(err))
		return
	}
	c.JSON(http.StatusOK, response.Register{
		Response: response.Ok,
		UserId:   userId,
		Token:    token,
	})
}

// UserInfo 查看用户信息
func UserInfo(ctx context.Context, c *app.RequestContext) {
	var userInfoParam param.UserInfo
	var err error
	userInfoParam.UserId, err = strconv.Atoi(c.Query("user_id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, response.ArgumentError(myerr.ArgumentInvalid(webutil.GetValidMsg(err, userInfoParam))))
		return
	}
	user, err := serviceimpl.NewUserService().UserInfo(userInfoParam.UserId)
	if err != nil {
		c.JSON(http.StatusBadRequest, response.ErrorResponse(err))
		return
	}
	c.JSON(http.StatusOK, response.UserInfo{
		Response: response.Ok,
		User:     *user,
	})
}
